package com.example.code.class02;

import java.util.HashMap;
import java.util.Map;

/**
 * @Date 2022/7/16
 * @Created by Jonathan
 */
public class Code03_ReceiveAndPrintOrderLine {

    public static void main(String[] args) {
        final MessageBox box = new MessageBox();
        box.receive(2, "B");
        box.receive(3, "C");
        box.receive(4, "D");
        box.receive(1, "A"); //print A B C D

    }


    static class MessageBox {

        static class Node {
            String info;
            Node next;

            public Node(String info) {
                this.info = info;
            }
        }


        private final Map<Integer, Node> headMap;
        private final Map<Integer, Node> tailMap;
        private Integer waitPoint;

        // 初始化头表和尾表
        public MessageBox() {
            headMap = new HashMap<>();
            tailMap = new HashMap<>();
            waitPoint = 1;
        }

        public void receive(Integer num, String info) {
            if (num < 1) {
                return;
            }

            Node cur = new Node(info);
            headMap.put(num, cur);
            tailMap.put(num, cur);

            // 查询某个连续区间以num-1结尾
            if (tailMap.containsKey(num - 1)) {
                tailMap.get(num - 1).next = cur;
                tailMap.remove(num - 1);
                headMap.remove(num);
            }

            // 查询有没有某个连续区间以num+1开头
            if (headMap.containsKey(num + 1)) {
                cur.next = headMap.get(num + 1);
                tailMap.remove(num);
                headMap.remove(num + 1);
            }

            if (num.equals(waitPoint)) {
                print();
            }
        }

        private void print() {
            Node node = headMap.get(waitPoint);
            headMap.remove(waitPoint);
            while (node != null) {
                System.out.print(node.info + " ");
                node = node.next;
                waitPoint++;
            }
            tailMap.remove(waitPoint - 1);
            System.out.println();
        }

    }


}
